<?php


namespace app\console\service\category;

use app\dao\goods\CategoryDao;

class CategoryQueryService
{
    //数据整合，父级包子级
    private function getChildrenList($data, $parent_id = 0, $page = 0, $perPage = 0)
    {
        $list = array();
        foreach ($data as $value)
        {
            if($value['parent_id'] == $parent_id)
            {
                $value['children'] = $this->getChildrenList($data, $value['id']);
                $list[] = $value;
            }
        }

        if ($perPage != 0 )
        {
            $page == 0 ? $start = $page : $start = ($page - 1) * $perPage;
            $page * $perPage > count($list) ? $end = count($list) :$end = $page * $perPage ;

            $pageList['pagination'] = ['page' => $page, 'perPage' => $perPage, 'total' => count($list)];
            $pageList['list'] = array();
            for ($i = $start; $i < $end;$i++)
            {
                array_push($pageList['list'],$list[$i]);
            }

            return $pageList;
        }

        return $list;
    }

    public function getPageListByType($type, $page, $perPage)
    {
        $categoryDao = new CategoryDao();
        $category = $categoryDao->getAllByType($type);

        $data = $this->getChildrenList($category['list']->toArray(), 0, $page, $perPage);

        return $data;
    }

    public function getListByType($type)
    {
        $categoryDao = new CategoryDao();
        $category = $categoryDao->getAllByType($type);

        $category['list'] = $this->getChildrenList($category['list']->toArray());

        return $category;
    }

}